package com.gxsf.back.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gxsf.back.pojo.Admin;
import com.gxsf.back.pojo.Notice;
import com.gxsf.back.repo.NoticeRepository;
import com.gxsf.back.util.JsonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.Map;

/**
 * @author BeijiRonin
 * @date 2020/11/12
 */
@CrossOrigin
@RestController
@RequestMapping("/notice_json")
@Slf4j
@Api("公告接口")
public class NoticeController {
    @Autowired
    NoticeRepository noticeRepository;

    @PostMapping("/delete")
    @ApiOperation("永久删除")
    public void delete(@RequestBody Map<String, String> map) {
        String noticeJson = map.get("notice");
        JSONObject jsonObject = JSONObject.parseObject(noticeJson);
        Notice notice = JSON.toJavaObject(jsonObject, Notice.class);
        noticeRepository.delete(notice);
    }

    @PostMapping("/add")
    @ApiOperation("新增一条公告")
    public Object add(@RequestBody Map<String, String> map) {
        String content = map.get("content");
        String adminJson = map.get("admin");
        Admin admin = JsonUtil.jsonToJava(adminJson, Admin.class);
        Notice notice = new Notice();
        notice.setContent(content);
        notice.setCreateTime(new Timestamp(System.currentTimeMillis()));
        notice.setAdminId(admin.getAdminId());
        return noticeRepository.save(notice);
    }
}
